<?php
namespace app\home\controller;

class Imgcode extends Common {
    public function index() {
        $width = 50;    //先定义图片的长、宽
        $height = isset($_REQUEST['height']) ? $_REQUEST['height'] : 18;
        $rand_str = "";
        $pattern = '0681236896895688900';

        for ($i = 0; $i < 4; $i++) {
            $rand_str .= $pattern{mt_rand(0, 18)};    //生成php随机数
        }

        session('valicode', strtolower($rand_str));//注册session

        $img = imagecreate($width, $height);//生成图片
        imagecolorallocate($img, 255, 255, 255);  //图片底色，ImageColorAllocate第1次定义颜色PHP就认为是底色了
        $black = imagecolorallocate($img, 127, 157, 185);

        for ($i = 1; $i <= 150; $i++) { //背景显示雪花的效果
            imagestring($img, 1, mt_rand(1, $width), mt_rand(1, $height), "8", imagecolorallocate($img, mt_rand(50, 255), mt_rand(200, 255), mt_rand(200, 255)));
        }

        for ($i = 0; $i < 4; $i++) { //加入文字
            imagestring($img, 5, $i * 10 + 6, 1, $rand_str[$i], imagecolorallocate($img, mt_rand(50, 200), mt_rand(100, 150), mt_rand(0, 200)));
        }

        imagerectangle($img, 0, 0, $width - 1, $height - 1, $black);//先成一黑色的矩形把图片包围

        if (function_exists("imagejpeg")) {
            header("content-type:image/jpeg\r\n");
            imagejpeg($img);
        } else {
            header("content-type:image/png\r\n");
            imagepng($img);
        }

        imagedestroy($img);
        exit;
    }
}
